package com.web.manager;

import com.web.utils.MDUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author FDjavaone
 */
@Service
@Slf4j
public class TokenManager {
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    public String login(String mobile, String password) {

        log.info(mobile + "-----" + password);

        /**
         * 判断是否登录成功 1.登录成功 1.1.成功生成对应的token并更新 1.2.失败就抛异常
         */
        Object token = stringRedisTemplate.opsForValue().get(mobile);
        String user = mobile + ":" + password;
        if (token == null) {
            log.info("新用户登录");
        } else {
            user = stringRedisTemplate.opsForValue().get(token);
            stringRedisTemplate.delete((String) token);
            log.info("更新用户登录token");
        }
        token = MDUtil.SHA1(mobile + password + System.currentTimeMillis());
        stringRedisTemplate.opsForValue().set((String) token, user, 15, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(mobile, (String) token, 15, TimeUnit.DAYS);
        return (String) token;
    }

}
